package com.sgb.kjwl.view.ui.activity.manage;

import static com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity.TYPE_IS_MYSELF;
import static com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity.WEBSITE_FOR_TEAM;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityEnterpriseAndMap3Binding;
import com.sgb.link.entity.PickFilterEntity;
import com.sgb.kjwl.model.entity.TwoLevelChildForPopWindowEntity;
import com.sgb.kjwl.model.entity.TwoLevelForPopWindowEntity;
import com.sgb.kjwl.model.entity.manage.TheEnterpriseOfEntity;
import com.sgb.kjwl.model.entity.self.PermissionMenuEntity;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.DialogHelper;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.manage.JingYingMapDataAdapter;
import com.sgb.kjwl.view.widget.EnterprisePopWindow;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.view.widget.TwoLevelEntityPopWindow;
import com.sgb.kjwl.viewmodel.manage.EnterpriseAndMapModel2;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.ui.activity.MemberApplyJoinActivity;
import com.sgb.member.ui.activity.MemberInviteJoinActivity;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 企业经营-地图查找
 */
public class EnterpriseAndMapActivity3 extends AppActivity implements LocationSource, AMapLocationListener,
        AMap.OnMarkerClickListener, GeocodeSearch.OnGeocodeSearchListener, AMap.OnCameraChangeListener {

    EnterpriseAndMapModel2 model;
    private ActivityEnterpriseAndMap3Binding binding;
    private String longitude, latitude, mIntroduction, type, text, areaCode = "", cityNos = "", price, dic = "3000", mOneLevelNo = "", mTwoLevelNo = "", name1 = "", name2 = "", name3 = "", mMapTitle = "";

    private List<PickSelectEntity<List<PickSelectEntity>>> list;

    private int mPage;
    private int lastPosition = -1;
    private ThreeLevelAreaWindow theEnterpriseOfAreaPopWindow;//省市弹窗
    private EnterprisePopWindow moneyPopWindow, distancePopWindow;
    private List<PickSelectEntity> typeData2 = new ArrayList<>(), distanceData = new ArrayList<>();
    private List<TheEnterpriseOfEntity> mapList = new ArrayList<>();//地图数据

    private TwoLevelEntityPopWindow<TwoLevelForPopWindowEntity> typePopWindow;//分类弹窗
    private String current_address = "";
    private AMap aMap;//地图对象

    //定位需要的声明
    private AMapLocationClient mLocationClient = null;//定位发起端
    private AMapLocationClientOption mLocationOption = null;//定位参数
    private OnLocationChangedListener mListener = null;//定位监听器
    private AMapLocation aMapLocation;
    private JingYingMapDataAdapter adapter;
    private boolean isAttention = false;
    private boolean isVisible = true;
    private String firstTabType = "";
    private String secondTabType = "";
    private int zoom = 14;
    private String city;
    private boolean isMyself;
    private boolean isShow = true;
    //申请的权限
    private ArrayList<PickFilterEntity<Object>> mApplyMenus = new ArrayList<>();

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, EnterpriseAndMapActivity3.class);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        aMap = binding.mapView.getMap();
        binding.mapView.onCreate(msavedInstanceState);
        //设置显示定位按钮 并且可以点击
        UiSettings settings = aMap.getUiSettings();
        //设置定位监听
        aMap.setLocationSource(this);
        // 是否显示定位按钮
        settings.setMyLocationButtonEnabled(false);
        settings.setZoomControlsEnabled(false);
        // 是否可触发定位并显示定位层
        aMap.setMyLocationEnabled(true);
        aMap.setOnMarkerClickListener(this);
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_weizhi_3));
        myLocationStyle.radiusFillColor(android.R.color.transparent);
        myLocationStyle.strokeColor(android.R.color.transparent);
        aMap.setMyLocationStyle(myLocationStyle);
        geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(this);

        aMap.setOnCameraChangeListener(this);
        //开始定位
        initLoc();
    }

    //定位
    private void initLoc() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
//        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }


    @Override
    protected void initView() {
        super.initView();
        isMyself = getIntent().getBooleanExtra(TYPE_IS_MYSELF, false);
        model = new ViewModelProvider(this).get(EnterpriseAndMapModel2.class);
        binding = DataBindingUtil.setContentView(EnterpriseAndMapActivity3.this, R.layout.activity_enterprise_and_map_3);
        binding.setLifecycleOwner(this);
        iniRecyclerView();
        initTabLayout();
        initLiveData();
        initButton();
        initSelect();
    }

    private void iniRecyclerView() {
        adapter = new JingYingMapDataAdapter(this, mapList);
        adapter.setCallback(new JingYingMapDataAdapter.Callback() {
            @Override
            public void back(TheEnterpriseOfEntity bean) {
                if (!TextUtils.isEmpty(bean.getSupplier())) {
                    WebsiteInfoActivity.start(getActivity(), bean.getSupplier(), 1);
                } else {
                    MToast.showToast(getActivity(), "公司no为空");
                }
            }

            @Override
            public void backHidden() {
                binding.rv.setVisibility(View.GONE);
                isVisible = false;
                lastPosition = -1;
                onShowPosition(-1);
            }

            @Override
            public void backAttention(TheEnterpriseOfEntity b) {
                isAttention = true;
                if (DialogHelper.checkLogin()) {
                    if (b.getFollow()) {
                        DialogHelper.showDialog(EnterpriseAndMapActivity3.this, "提示", "确定取消关注该企业？", "取消关注", new DialogFunction() {
                            @Override
                            public void normalRoundDialog() {
                                model.follow(b.getSupplier(), EnterpriseAndMapActivity3.this);
                            }
                        });
                    } else {
                        model.follow(b.getSupplier(), EnterpriseAndMapActivity3.this);
                    }
                } else {
                    VerificationCodeLoginActivity.start(EnterpriseAndMapActivity3.this, EventConstant.EVENT_MANAGE);
                }
            }

            @Override
            public void backJiaMeng(TheEnterpriseOfEntity bean) {
                if (DialogHelper.checkLogin()) {
                    inviteJoin(bean);
                } else {
                    VerificationCodeLoginActivity.start(EnterpriseAndMapActivity3.this, EventConstant.EVENT_MANAGE);
                }
            }

            @Override
            public void backApply(TheEnterpriseOfEntity bean) {
                if (DialogHelper.checkLogin()) {
                    doApply(bean);
                } else {
                    VerificationCodeLoginActivity.start(EnterpriseAndMapActivity3.this, EventConstant.EVENT_MANAGE);
                }
            }

            @Override
            public void backHanXun(TheEnterpriseOfEntity bean) {
                if (DialogHelper.checkLogin()) {
                    if (!isMyself) {
                        postInquiry(bean);
                    }
                } else {
                    VerificationCodeLoginActivity.start(EnterpriseAndMapActivity3.this, EventConstant.EVENT_MANAGE);
                }
            }
        });
        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(binding.rv);
        binding.rv.setAdapter(adapter);
        binding.rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    //获取完全显示的ItemPosition
                    int lastVisibleItem = linearLayoutManager.findLastCompletelyVisibleItemPosition();
                    if (lastPosition != lastVisibleItem) {
                        lastPosition = lastVisibleItem;
                        onShowPosition(lastVisibleItem);
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

            }
        });
    }


    private void onShowPosition(int position) {
        aMap.clear();
        for (int i = 0; i < mapList.size(); i++) {
            mapList.size();
            TheEnterpriseOfEntity entity = mapList.get(i);
            if (null != entity && !TextUtils.isEmpty(entity.getLatitude()) && !TextUtils.isEmpty(entity.getLongitude())) {
                double currentLat = Double.parseDouble(entity.getLatitude());
                double currentLong = Double.parseDouble(entity.getLongitude());
                if (currentLat != 0 && currentLong != 0) {
                    LatLng latLng = new LatLng(currentLat, currentLong);
                    if (i == position) {
                        markerOption1 = new MarkerOptions().icon(BitmapDescriptorFactory.fromView(setMarkStyle(true)))
                                .position(latLng)
                                .title(i + "")
                                .infoWindowEnable(false)
                                .draggable(true);
                        aMap.addMarker(markerOption1);
                        aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
                    } else {
                        markerOption1 = new MarkerOptions().icon(BitmapDescriptorFactory.fromView(setMarkStyle(false)))
                                .position(latLng)
                                .title(i + "")
                                .infoWindowEnable(false)
                                .draggable(true);
                        aMap.addMarker(markerOption1);
                    }
                }
            }
        }
        addLocalMarker();
    }


    private void initTabLayout() {
        binding.tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mIntroduction = list.get(tab.getPosition()).getNo();
                firstTabType = list.get(tab.getPosition()).getPickerViewText();
                adapter.setFirstTabType(firstTabType);
                if(!binding.tlCompanyTradesType.getTabAt(0).isSelected()){
                    binding.tlCompanyTradesType.getTabAt(0).select();
                }else {
                     loadComData(false);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                binding.llTop.setVisibility(View.VISIBLE);
                binding.llAddr.setVisibility(View.VISIBLE);
            }
        });

        binding.tlCompanyTradesType.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                type = typeData2.get(tab.getPosition()).getNo();
                secondTabType = typeData2.get(tab.getPosition()).getPickerViewText();
                adapter.setSecondTabType(secondTabType);
                loadComData(false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                binding.llTop.setVisibility(View.VISIBLE);
                binding.llAddr.setVisibility(View.VISIBLE);
            }
        });
    }

    private void initButton() {
        binding.ivBack.setOnClickListener(v -> finish());
        binding.tvDistance.setOnClickListener(this);
        binding.tvArea.setOnClickListener(this);
        binding.tvType.setOnClickListener(this);
        binding.tvPersonNumber.setOnClickListener(this);
        binding.tvAddr.setOnClickListener(this);
        binding.ivCurrentAddr.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_area:
                binding.tvArea.contentSelect(false, true);
                showProvincePopWindow();
                break;
            case R.id.tv_person_number:
                binding.tvPersonNumber.contentSelect(false, true);
                showPerson();
                break;
            case R.id.tv_distance:
                binding.tvDistance.contentSelect(false, true);
                showDistancePopWindowPopWindow();
                break;
            case R.id.tv_type:
                binding.tvType.contentSelect(false, true);
                showType();
                break;
            case R.id.tv_addr:
                if(TextUtils.isEmpty(latitude)||TextUtils.isEmpty(longitude)){
                    Toast.makeText(getActivity(), "未获取到定位！", Toast.LENGTH_SHORT).show();
                    return;
                }
                JingYingMapSearchActivity.start(this, Double.parseDouble(latitude), Double.parseDouble(longitude), current_address, city);
                break;
            case R.id.iv_current_addr:
                if (aMapLocation != null) {
                    theEnterpriseOfAreaPopWindow.resetDataAndUI();
                    latitude = aMapLocation.getLatitude() + "";
                    longitude = aMapLocation.getLongitude() + "";
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(zoom));
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                    binding.tvAddr.setText(current_address);
                    loadComData(false);
                }else {
                    Toast.makeText(getActivity(), "未获取到定位！", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == 1) {
            Bundle bundle = data.getExtras();
            String addr = bundle.getString("addr");
            double lat = bundle.getDouble("lat");
            double lon = bundle.getDouble("lon");
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(lat, lon)));
            binding.tvAddr.setText(addr);
            longitude = lon + "";
            latitude = lat + "";
            isAttention = false;

            loadComData(false);
        }
    }

    @Override
    protected void init() {
        super.init();
        model.getCityData(this);
        model.getTradeTypes(this);
        model.getType(this);
        model.findCapitalList(this);
        model.getDistanceDatas();
        model.getTypeList(this);
        model.getPermissionMenu(1);
    }


    private void initSelect() {
        typePopWindow = new TwoLevelEntityPopWindow<>(getActivity());
        typePopWindow.setBgView(binding.grayLayout);
        typePopWindow.setmTwoLevelClick(new TwoLevelEntityPopWindow.TwoLevelClick<TwoLevelForPopWindowEntity>() {
            @Override
            public void oneClick(TwoLevelChildForPopWindowEntity<List<TwoLevelForPopWindowEntity>> d, int position) {
                name3 = d.getName();
                if (!mOneLevelNo.equals(d.getId())) {
                    mTwoLevelNo = "";
                }
                mOneLevelNo = d.getId();
            }

            @Override
            public void twoClick(TwoLevelForPopWindowEntity twoLevelEntityForPopWindow, int position) {
                name3 = twoLevelEntityForPopWindow.getName();
                mTwoLevelNo = twoLevelEntityForPopWindow.getId();
            }

            @Override
            public void reset() {
                typePopWindow.dismiss();
                loadComData(false);
            }
        });

        typePopWindow.setOnResultClick((key1, key2, key3) -> loadComData(false));
        typePopWindow.setOnDismissListener(() -> binding.tvType.contentSelect(!name3.equals("不限") && !name3.equals(""), false));

        // 省 城市
        theEnterpriseOfAreaPopWindow = new ThreeLevelAreaWindow(getActivity()) {
            @Override
            protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                super.provinceClick(baseAreaEntity, position);
                name1 = baseAreaEntity.getSimpleName();
                if (!areaCode.equals(baseAreaEntity.getId())) {
                    cityNos = "";
                }
                areaCode = baseAreaEntity.getId();
            }

            @Override
            protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                super.cityClick(baseAreaEntity, position);
                cityNos = baseAreaEntity.getId();
                name1 = baseAreaEntity.getSimpleName();
            }

            @Override
            protected void reset() {
                super.reset();
                theEnterpriseOfAreaPopWindow.dismiss();
            }
        };
        theEnterpriseOfAreaPopWindow.setBgView(binding.grayLayout);
        theEnterpriseOfAreaPopWindow.setThreeListIsGone(true);
        theEnterpriseOfAreaPopWindow.setProvinceSingle();
        theEnterpriseOfAreaPopWindow.setCitySingle();
        theEnterpriseOfAreaPopWindow.setOnResultClick((key1, key2, key3) -> loadComData(false));
        theEnterpriseOfAreaPopWindow.setOnDisMissClick(() -> {
            binding.tvArea.contentSelect(!name1.equals("") && (!name1.equals("不限")), false);
            if (areaCode.equals("")) {
                binding.tvArea.contentSelect(false, false);
            }

            if (name1.equals("不限") && TextUtils.isEmpty(areaCode)) {
                latitude = aMapLocation.getLatitude() + "";
                longitude = aMapLocation.getLongitude() + "";
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude))));
                current_address = aMapLocation.getAddress();
                binding.tvAddr.setText(current_address);
            } else {
                model.getLocationLL(this, areaCode, cityNos, "");
            }
        });

        // 注册资金
        moneyPopWindow = new EnterprisePopWindow(getActivity());
        moneyPopWindow.setBgView(binding.grayLayout);
        moneyPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                price = (String) key1;
                name2 = (String) key2;
                //请求接口
                loadComData(false);
            }
        });
        moneyPopWindow.setOnDisMissClick(() -> binding.tvPersonNumber.contentSelect(!name2.equals("") && !name2.equals("不限"), false));
        // 距离
        distancePopWindow = new EnterprisePopWindow(getActivity());
        distancePopWindow.setBgView(binding.grayLayout);
        distancePopWindow.setOnResultClick((key1, key2, key3) -> {
            try {
                String distance = (String) key1;
                if (!distance.equals("")) {
                    dic = Long.valueOf(distance) * 1000 + "";
                } else {
                    dic = distance;
                }
                name3 = (String) key2;
                getZoom(dic);
                aMap.moveCamera(CameraUpdateFactory.zoomTo(zoom));
                //请求接口
                loadComData(false);
            } catch (Exception e) {
                MToast.showToast(getActivity(), "您输入的数字太大");
            }
        });
        distancePopWindow.setOnDisMissClick(() -> binding.tvDistance.contentSelect(!name3.equals("") && !name3.equals("默认"), false));
    }

    /**
     * 设置缩放比
     *
     * @param distance
     */
    private void getZoom(String distance) {
        int dis = Integer.parseInt(distance);
        if (dis < 10000) {
            zoom = 14;
        } else if (10000 <= dis && dis < 20000) {
            zoom = 13;
        } else if (20000 <= dis && dis < 30000) {
            zoom = 12;
        } else if (30000 <= dis && dis < 40000) {
            zoom = 11;
        } else if (40000 <= dis && dis < 50000) {
            zoom = 10;
        } else if (50000 <= dis && dis < 60000) {
            zoom = 9;
        } else if (60000 <= dis && dis < 70000) {
            zoom = 8;
        } else if (70000 <= dis) {
            zoom = 7;
        }
    }

    private void showProvincePopWindow() {
        theEnterpriseOfAreaPopWindow.showPopwindow(binding.llTop, 0, 0);
    }

    private void showDistancePopWindowPopWindow() {
        distancePopWindow.showPopwindow(binding.llTop, 0, 0);
    }


    private MarkerOptions markerOption1;

    private void addMarkInfoWindow2(List<TheEnterpriseOfEntity> datas) {
        try {
            aMap.clear();
            mapList.clear();
            if (datas.size() == 0) {
                MToast.showToast(this, "暂无数据");
                isVisible = false;
                binding.rv.setVisibility(View.GONE);
                lastPosition = -1;
                isShow = false;
                return;
            }
            for (int i = 0; i < datas.size(); i++) {
                datas.size();
                TheEnterpriseOfEntity entity = datas.get(i);
                if (null != entity && !TextUtils.isEmpty(entity.getLatitude()) && !TextUtils.isEmpty(entity.getLongitude())) {
                    double currentLat = Double.parseDouble(entity.getLatitude());
                    double currentLong = Double.parseDouble(entity.getLongitude());
                    if (currentLat != 0 && currentLong != 0) {
                        LatLng latLng = new LatLng(currentLat, currentLong);
                        if (i == 0) {
                            markerOption1 = new MarkerOptions().icon(BitmapDescriptorFactory.fromView(setMarkStyle(true)))
                                    .position(latLng)
                                    .title(i + "")
                                    .infoWindowEnable(false)
                                    .draggable(true);
                            aMap.addMarker(markerOption1);
                            isVisible = true;
                            binding.rv.setVisibility(View.VISIBLE);
                            lastPosition = 0;
                            aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
                        } else {
                            markerOption1 = new MarkerOptions().icon(BitmapDescriptorFactory.fromView(setMarkStyle(false)))
                                    .position(latLng)
                                    .title(i + "")
                                    .infoWindowEnable(false)
                                    .draggable(true);
                            aMap.addMarker(markerOption1);
                        }
                        mapList.add(datas.get(i));
                    }
                }
            }
            adapter.notifyDataSetChanged();
            binding.rv.scrollToPosition(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void upDateRecyclerView(List<TheEnterpriseOfEntity> datas) {
        try {
            mapList.clear();
            if (datas.size() == 0) {
                return;
            }
            for (int i = 0; i < datas.size(); i++) {
                datas.size();
                TheEnterpriseOfEntity entity = datas.get(i);
                if (null != entity && !TextUtils.isEmpty(entity.getLatitude()) && !TextUtils.isEmpty(entity.getLongitude())) {
                    double currentLat = Double.parseDouble(entity.getLatitude());
                    double currentLong = Double.parseDouble(entity.getLongitude());
                    if (currentLat != 0 && currentLong != 0) {
                        mapList.add(datas.get(i));
                    }
                }
            }
            adapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    MarkerOptions markerOption;

    private void addLocalMarker() {
        markerOption = new MarkerOptions()
                .position(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)))
                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_weizhi_3))
                .period(10000)
                .draggable(true);
        aMap.addMarker(markerOption).hideInfoWindow();
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        int mPosition = Integer.parseInt(marker.getTitle());
        if (mPosition != lastPosition) {
            lastPosition = mPosition;
            if (!isVisible) {
                isVisible = true;
                binding.rv.setVisibility(View.VISIBLE);
            }
            onShowPosition(mPosition);
            binding.rv.scrollToPosition(mPosition);
        }
        return false;
    }

    private View setMarkStyle(boolean isBigMarkView) {
        View markerView = LayoutInflater.from(getActivity()).inflate(R.layout.view_marker_2, null);
        ImageView imageView = markerView.findViewById(com.sgb.alimaplibrary.R.id.marker);
        Drawable drawable = getResources().getDrawable(isBigMarkView ? R.mipmap.icon_big : R.mipmap.icon_small);
        imageView.setImageDrawable(drawable);
        return markerView;
    }

    private void showType() {
        typePopWindow.showPopwindow(binding.llTop, 0, 0);
    }


    private void initLiveData() {
        model.mCom.observe(this, theEnterpriseOfEntities -> {
            if (isAttention) {
                upDateRecyclerView(theEnterpriseOfEntities);
                isAttention = false;
            } else {
                isShow = true;
                binding.llTop.setVisibility(View.VISIBLE);
                binding.llAddr.setVisibility(View.VISIBLE);
                addMarkInfoWindow2(theEnterpriseOfEntities);
                addLocalMarker();
            }
        });

        model.mDistance.observe(this, pickSelectEntities -> {
            distanceData.clear();
            distanceData.addAll(pickSelectEntities);
            distancePopWindow.setData(distanceData, true, false);
        });

        model.mCapital.observe(this, pickSelectEntities -> {
            moneyPopWindow.setData(pickSelectEntities);
        });

        model.mCity.observe(this, addressEntities -> {
            theEnterpriseOfAreaPopWindow.setDataForCompany(addressEntities, true);
        });

        model.mFollow.observe(this, aBoolean -> {
            loadComData(false);
        });

        model.mTradeType.observe(this, twoLevelChildForPopWindowEntities -> typePopWindow.setData(twoLevelChildForPopWindowEntities));

        model.mType.observe(this, pickSelectEntities -> {
            typeData2 = pickSelectEntities;
            for (PickSelectEntity data : pickSelectEntities) {
                binding.tlCompanyTradesType.addTab(binding.tlCompanyTradesType.newTab().setText(data.getPickerViewText()));
            }
        });

        model.mTypeFirst.observe(this, pickSelectEntities -> {
            list = pickSelectEntities;
            for (PickSelectEntity<List<PickSelectEntity>> pickSelectEntity : pickSelectEntities) {
                TabLayout.Tab tab = binding.tablayout.newTab();
                tab.setText(pickSelectEntity.getPickerViewText());
                binding.tablayout.addTab(tab);

            }
        });
        model.locationLiveData.observe(this, bean -> {
            if (!TextUtils.isEmpty(bean.getLng())) {
                latitude = bean.getLat();
                longitude = bean.getLng();
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude))));
                getAddress(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)));
                loadComData(false);
            }
        });
        //网站底部区域审核权限
        model.mCheckMenusLiveData.observe(this, pickFilterEntities -> {
            mApplyMenus.clear();
            mApplyMenus.addAll(pickFilterEntities);
        });
    }

    private GeocodeSearch geocoderSearch;

    private void getAddress(LatLng latLng) {
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
    }


    private void showPerson() {
        moneyPopWindow.showPopwindow(binding.llTop, 0, 0);
    }

    private void loadComData(boolean isLoadMore) {
        if (!TextUtils.isEmpty(latitude) && !TextUtils.isEmpty(firstTabType) && !TextUtils.isEmpty(secondTabType)) {
            if (!isAttention) {
                binding.rv.setVisibility(View.GONE);
                isVisible = false;
            }
            lastPosition = -1;
            Map<String, Object> map = new HashMap<>();
            mPage = !isLoadMore ? 1 : mPage + 1;
            map.put("page", mPage);
            map.put("limit", "20");
            map.put("industryCategory2", mTwoLevelNo);//行业分类
            map.put("industryCategory1", mOneLevelNo);//行业分类
            map.put("areaNo", cityNos);//城市编号
            map.put("provinceNo", areaCode);//省号
            map.put("staffNumber", price);//人数
            map.put("distance", dic);//距离
            map.put("dictId", type);//二级分类的
            map.put("longitude", longitude);
            map.put("latitude", latitude);
            map.put("name", text);
            map.put("serviceType", mIntroduction);//一级分类的编号
            model.getComList(map, EnterpriseAndMapActivity3.this);
        }
    }


    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                this.aMapLocation = amapLocation;
                mLocationClient.stopLocation();
                latitude = amapLocation.getLatitude() + "";
                longitude = amapLocation.getLongitude() + "";
                city = amapLocation.getCity();
                current_address = amapLocation.getAddress();
                binding.tvAddr.setText(current_address);
                aMap.moveCamera(CameraUpdateFactory.zoomTo(zoom));
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude())));
                loadComData(false);
            }
        }
    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
    }

    @Override
    public void deactivate() {
        mListener = null;
    }

    @Override
    public void onResume() {
        super.onResume();
        binding.mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        binding.mapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding.mapView.onDestroy();
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int i) {
        if (i == 1000) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                String addressName = result.getRegeocodeAddress().getFormatAddress();
                binding.tvAddr.setText(addressName);
            }
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    /**
     * 申请
     *
     * @param enterpriseOfEntity
     */
    private void doApply(TheEnterpriseOfEntity enterpriseOfEntity) {
        if (isMyself) {
            AgentApplyActivity.Companion.launch(this, mApplyMenus);
        } else {
            //int mType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
            if (getPermission("14_shenqingguanli")) {
                QualityMemberBean bean = new QualityMemberBean();
                bean.setCompanyNo(enterpriseOfEntity.getSupplier());
                bean.setCompanyName(enterpriseOfEntity.getSupplierName());
                MemberApplyJoinActivity.start(EnterpriseAndMapActivity3.this, bean);
            } else {
                MToast.showToast(EnterpriseAndMapActivity3.this, "您当前为个人/团队身份，暂不支持该操作");
            }
        }
    }

    //邀请加盟
    private void inviteJoin(TheEnterpriseOfEntity entity) {
        if (entity == null) {
            return;
        }

        if (getPermission("14_yaoqingguanli")) {
            QualityMemberBean bean1 = new QualityMemberBean();
            bean1.setCompanyNo(entity.getSupplier());
            bean1.setCompanyName(entity.getSupplierName());
            bean1.setServiceTypeName(entity.getServiceType());
            bean1.setServiceType(entity.getServiceType());
            MemberInviteJoinActivity.start(this, bean1);
        } else {
            MToast.showToast(this, "您当前为个人/团队身份，暂不支持该操作");
        }
    }

    /**
     * 权限判断
     */
    private Boolean getPermission(String title) {
        if (model.permission_list != null)
            for (PermissionMenuEntity entity : model.permission_list) {
                if ("oneLevel_huiyuanjingying".equals(entity.getName())) {//会员经营
                    for (PermissionMenuEntity.ListEntity entity1 : entity.getList()) {
                        if (TextUtils.equals(entity1.getName(), "twoLevel_huiyuanguanli")) {//会员管理
                            if (entity1.getList() != null && !entity1.getList().isEmpty()) {
                                for (PermissionMenuEntity.ListEntity entity2 : entity1.getList()) {
                                    if (entity2.getName().equals(title)) {
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        return false;
    }

    //发起函询
    private void postInquiry(TheEnterpriseOfEntity entity) {
        //发起人的身份是团队
        if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1) == WEBSITE_FOR_TEAM) {
            MToast.showToast(this, "功能开发中，敬请期待");
            return;
        }
        if (1 == WEBSITE_FOR_TEAM) {
            MToast.showToast(this, "功能开发中，敬请期待");
            return;
        }
        if (entity == null) {
            return;
        }

        WebSitePostInquiryActivity.Companion.start(this, entity.getSupplierName(), entity.getSupplier(), 1);
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        if (!isShow) {
            binding.llTop.setVisibility(View.GONE);
            binding.llAddr.setVisibility(View.GONE);
        }
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        isShow = false;
    }
}
